<?php namespace Phpcmf\Controllers;

class Tag extends \Phpcmf\Common
{

	public function index()
	{
		// 获取tag数据
		$tag = dr_safe_replace(urldecode(\Phpcmf\Service::L('Input')->get('name')));
		!$tag && exit($this->goto_404_page(dr_lang('Tag参数不存在')));

		$name = 'tag_'.SITE_ID.'-'.$tag;
		list($data, $parent, $related) = \Phpcmf\Service::L('cache')->init()->get($name);
		if (!$data) {
			$rule = \Phpcmf\Service::L('cache')->get('urlrule', SITE_REWRITE, 'value');
			$join = $rule['catjoin'] ? $rule['catjoin'] : '/';
			$tag = @end(@explode($join, $tag)); // 转换tag值
			$cache = \Phpcmf\Service::L('cache')->get('tag-'.SITE_ID);
			if ($cache[$tag]) {
				$data = \Phpcmf\Service::M('Tag')->tag_row($cache[$tag]['id']);
				// 格式化显示
				$data = \Phpcmf\Service::L('Field')->format_value(\Phpcmf\Service::L('cache')->get('tag-'.SITE_ID.'-field'), $data);
				$parent = $related = [];
				// 是否存在子tag
				if ($cache[$tag]['codes']) {
					$parent = [];
					$related[$tag] = $cache[$tag];
					foreach ($cache[$tag]['codes'] as $t) {
						$related[$t] = $cache[$t];
					}
				} elseif ($cache[$tag]['pid'] && $cache[$cache[$tag]['pid']]) {
					// 本身就是子词
					$parent = $cache[$cache[$tag]['pid']];
					$related[$cache[$tag]['pid']] = $cache[$cache[$tag]['pid']];
					foreach ($cache[$cache[$tag]['pid']]['codes'] as $t) {
						$related[$t] = $cache[$t];
					}
				}
				// 合并缓存数据
				$data['tags'] = $cache[$tag]['tags'];
                SYS_CACHE && \Phpcmf\Service::L('cache')->init()->save($name, [$data, $parent, $related], SYS_CACHE_SHOW * 3600);
			}
		}

		!$data && $data = ['code' => $tag, 'name' => $tag, 'tags' => $tag];

		\Phpcmf\Service::V()->assign(array(
			'tag' => $data,
			'parent' => $parent,
			'related' => $related,
			'meta_title' => $data['name'].SITE_SEOJOIN.SITE_NAME,
			'meta_keywords' => $this->get_cache('site', SITE_ID, 'seo', 'SITE_KEYWORDS'),
			'meta_description' => $this->get_cache('site', SITE_ID, 'seo', 'SITE_DESCRIPTION')
		));
		\Phpcmf\Service::V()->display('tag.html');
	}

}
